package com.szgd.controller.gatherEquip;

import com.sun.corba.se.spi.ior.iiop.IIOPFactories;
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import com.szgd.controller.BaseController;
import com.szgd.hikvision.HikvisionUtil;
import com.szgd.hikvision.MonitorCameraInfo;
import com.szgd.paging.Order;
import com.szgd.paging.PageBounds;
import com.szgd.service.equipment.EquipmentService;
import com.szgd.service.gatherEquip.CameraService;
import com.szgd.util.FileUtil;
import com.szgd.util.PropertiesUtil;
import com.szgd.util.StringUtil;
import com.szgd.util.SysUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/camera")
public class CameraController extends BaseController {
    private static Logger logger = Logger.getLogger(CameraController.class);
    private  String bidId;
    private  String siteId;
    @Autowired
    CameraService cameraService;
    @Autowired
    FileUtil fileUtil;
    /**
     * 摄像头监控列表页面
     * @param request
     * @param session
     * @return
     */
    @RequestMapping(value = "toCameraMonitorList", method = RequestMethod.GET)
    public ModelAndView toCameraMonitorList(HttpServletRequest request, HttpSession session) {
        ModelAndView mv = this.getModelAndView(request,session,"gatherEquip/camera/cameraMonitorList");
        return mv;
    }

    /**
     * 摄像头列表
     * @param request
     * @param session
     * @return
     */
    @RequestMapping(value = "toCameraList", method = RequestMethod.GET)
    public ModelAndView toCameraList(HttpServletRequest request, HttpSession session) {
        ModelAndView mv = this.getModelAndView(request,session,"gatherEquip/camera/cameraList");
        mv.addObject("bidId",bidId);
        mv.addObject("siteId",siteId);
        return mv;
    }

    /**摄像头查看
     *
     * @param request
     * @param session
     * @return
     */
    @RequestMapping(value = "toCameraView", method = RequestMethod.GET)
    public ModelAndView toCameraView(HttpServletRequest request, HttpSession session)
    {
        ModelAndView mv = getModelAndView(request,session,"gatherEquip/camera/cameraView");
        String id = mv.getModelMap().get("id")== null?"":mv.getModelMap().get("id").toString().replace("null","");
        if (id.length() > 0)//修改
        {
            Map<String, Object> cameraInfoMap = cameraService.getCameraInfo(id);
            mv.addObject("camera",cameraInfoMap);
        }
        return mv;
    }

    /**
     * 打开摄像头监控页面
     * @param request
     * @param session
     * @return
     */
    @RequestMapping(value = "toCameraMonitor", method = RequestMethod.GET)
    public ModelAndView toCameraMonitor(HttpServletRequest request, HttpSession session)
    {
        ModelAndView mv = getModelAndView(request,session,"gatherEquip/camera/cameraMonitor");
        String id = mv.getModelMap().get("id")== null?"":mv.getModelMap().get("id").toString().replace("null","");
        if (id.length() > 0)//修改
        {
            Map<String, Object> cameraInfoMap = cameraService.getCameraInfo(id);
            mv.addObject("camera",cameraInfoMap);
        }
        return mv;
    }

    /**
     * 摄像头增加、修改页面
     * @param request
     * @param session
     * @return
     */
    @RequestMapping(value = "toCameraForm", method = RequestMethod.GET)
    public ModelAndView toCameraForm(HttpServletRequest request, HttpSession session)
    {
        ModelAndView mv = getModelAndView(request,session,"gatherEquip/camera/cameraForm");
        Map<String, Object> cameraInfoMap  = new HashMap<>();
        String id = mv.getModelMap().get("id")== null?"":mv.getModelMap().get("id").toString().replace("null","");
        if (id.length() > 0)//修改
        {
            cameraInfoMap = cameraService.getCameraInfo(id);
        }
        mv.addObject("camera",cameraInfoMap);
        return mv;
    }

    @RequestMapping(value = "/getCameraList", method = RequestMethod.GET)
    public void  getCameraList(HttpServletResponse response, HttpServletRequest request){
        Map<String, Object> paramMap = getMapParams(request);
        bidId = paramMap.get("bidId") == null?"":paramMap.get("bidId").toString();
        siteId = paramMap.get("siteId") == null?"":paramMap.get("siteId").toString();
        List<Map<String, Object>> dataList = cameraService.getCameraList(paramMap);
        outTableJSONDataCommon(response, dataList);
    }

    @RequestMapping(value = "/getCameraThumbnailList", method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object>  getCameraThumbnailList(HttpServletResponse response, HttpServletRequest request){
        Map<String, Object> paramMap = getMapParams(request);
        String siteId = paramMap.get("siteId")==null?"":paramMap.get("siteId").toString().replace("null","");
        if(siteId.length() == 0){
            paramMap.put("siteId",null);
        }
        List<Map<String, Object>>  dataList = cameraService.getCameraInfoListNoPage(paramMap);
        Map<String,Object> result = new HashMap<>();
        result.put("data",dataList);
        result.put("totalNum",dataList.size());
        return getSuccMap(result);
    }

    @RequestMapping(value = "/saveCamera")
    @ResponseBody
    public Map<String,Object> saveCamera(@RequestBody HashMap<String, Object> paramMap, HttpServletRequest request, HttpServletResponse response) {
        String id = paramMap.get("id")== null?"":paramMap.get("id").toString().replace("null","");
        String message = "";
        try {
            Map<String, Object> param1 = new HashMap<>();
            param1.put("ip",paramMap.get("ip"));
            List<Map<String, Object>>  cameraInfoList = cameraService.getCameraInfoListNoPage(param1);
            if (cameraInfoList != null && cameraInfoList.size() > 0)
            {
                boolean isHave = true;
                if (id.length() != 0)
                {
                    Map<String, Object> cameraInfoMap = cameraInfoList.get(0);
                    String tempId = cameraInfoMap.get("id").toString();
                    if (id.equalsIgnoreCase(tempId))
                    {
                        isHave = false;
                    }
                }
                if (isHave)
                {
                    message = "表里已经存在相同IP!";
                    return getErrorMap(message);
                }

            }
            if (id.length() == 0)//新增
            {
                paramMap.put("creator",this.getLoginId(request.getSession()));
                cameraService.insertCameraInfo(paramMap);
                message = "摄像头信息新增成功！";
            } else {
                paramMap.put("uploader",this.getLoginId(request.getSession()));
                cameraService.updateCameraInfo(paramMap);
                message = "摄像头信息保存成功！";
            }
            return getSuccMap(message);
        }catch(Exception e){
            e.printStackTrace();
            logger.error("摄像头信息保存失败："+e.getMessage());
            return getSuccMap("摄像头信息保存失败："+e.getMessage());
        }
    }

    @RequestMapping(value = "/deleteCamera", method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> deleteCamera(@RequestBody HashMap<String, Object> paramMap, HttpServletRequest request, HttpServletResponse response) {
        try{
            paramMap.put("uploader",this.getLoginId(request.getSession()));
            cameraService.updateCameraInfo(paramMap);

            String message = "摄像头删除成功！";
            return getSuccMap(message);
        }catch (Exception e)
        {
            e.printStackTrace();
            logger.error("摄像头删除失败："+e.getMessage());
            return getSuccMap("摄像头删除失败："+e.getMessage());
        }
    }

    @RequestMapping(value = "/saveCapturePic")
    @ResponseBody
    public Map<String,Object> saveCapturePic(@RequestBody HashMap<String, Object> paramMap,HttpServletRequest request,HttpServletResponse response) {
        try {
            String ip = paramMap.get("ip")==null?null:paramMap.get("ip").toString();
            int innerPort = paramMap.get("innerPort").toString().length()==0?8000:Integer.parseInt(paramMap.get("innerPort").toString());
            String loginUserName = paramMap.get("loginUserName").toString();
            String loginPassword = paramMap.get("loginPassword").toString();

            MonitorCameraInfo cameraInfo = new MonitorCameraInfo();
            cameraInfo.setCameraIp(ip);
            cameraInfo.setCameraPort((short)innerPort);
            cameraInfo.setUserName(loginUserName);
            cameraInfo.setUserPwd(loginPassword);
            HikvisionUtil hikvisionUtil = new HikvisionUtil();
            String fileName= hikvisionUtil.getDVRPic(cameraInfo,PropertiesUtil.get("snapImagePath"));


            if (fileName == null)
                return getErrorMap("摄像头抓拍图片失败！");
            else
            {
                paramMap.put("path",SysUtil.getDateStr(null,"yyyyMM"));
                paramMap.put("fileName",fileName);
                cameraService.updateCameraInfo(paramMap);
                return getSuccMap("摄像头抓拍图片保存成功！");
            }

        }catch(Exception e){
            e.printStackTrace();
            return getSuccMap("摄像头抓拍图片保存失败："+e.getMessage());
            //throw new Exception("人员信息保存失败："+e.getMessage());
        }
    }

    @RequestMapping(value = "/showSnapPic", method = RequestMethod.GET)
    @ResponseBody
    public String showSnapPic(HttpServletRequest request, HttpServletResponse response) {

        try {

            String fileName = URLDecoder.decode(request.getParameter("fileName"),"utf-8");
            String picPath = request.getParameter("path");
            //String id = request.getParameter("id");
            OutputStream outputStream = response.getOutputStream();
            response.setContentType("application/octet-stream ");
            response.setHeader("Connection", "close"); // 表示不能用浏览器直接打开
            response.setHeader("Accept-Ranges", "bytes");// 告诉客户端允许断点续传多线程连接下载
            response.setContentType("multipart/form-data");
            response.setContentType("UTF-8");

            //Map<String, Object>  cameraInfo = cameraService.getCameraInfo(id);
            String subPath = picPath;//cameraInfo.get("path").toString();
            //String fileName = cameraInfo.get("fileName").toString();
            String fileUploadPath = PropertiesUtil.get("snapImagePath");
            String filePath =   fileUploadPath + File.separator + subPath ;;
            InputStream inputStream = new FileInputStream(filePath +  File.separator + fileName);
            int len = 0;
            byte[] buf = new byte[1024];
            while ((len = inputStream.read(buf, 0, 1024)) != -1) {
                outputStream.write(buf, 0, len);
            }
            outputStream.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
